package com.java110.mall.cart.bmo.storeOrderCart.impl;

import com.java110.mall.cart.bmo.storeOrderCart.IUpdateStoreOrderCartBMO;
import com.java110.mall.cart.storeOrderEngine.StoreOrderShareAcct;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.shop.ShopDistributionModeDto;
import com.java110.dto.storeOrder.StoreOrderDto;
import com.java110.dto.storeOrder.StoreOrderCartDto;
import com.java110.dto.storeOrder.StoreOrderCartEventDto;
import com.java110.dto.storeOrder.StoreOrderCartSendDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.acct.IAccountInnerServiceSMO;
import com.java110.intf.cart.IStoreOrderCartEventInnerServiceSMO;
import com.java110.intf.cart.IStoreOrderCartInnerServiceSMO;
import com.java110.intf.cart.IStoreOrderCartSendInnerServiceSMO;
import com.java110.intf.cart.IStoreOrderInnerServiceSMO;
import com.java110.intf.goods.IShopDistributionModeInnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.storeOrder.StoreOrderCartPo;
import com.java110.po.storeOrder.StoreOrderCartEventPo;
import com.java110.po.storeOrder.StoreOrderCartSendPo;
import com.java110.po.storeOrder.StoreOrderPo;
import com.java110.utils.lock.DistributedLock;
import com.java110.utils.util.Assert;
import com.java110.utils.util.DateUtil;
import com.java110.utils.util.ListUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("updateStoreOrderCartBMOImpl")
public class UpdateStoreOrderCartBMOImpl implements IUpdateStoreOrderCartBMO {

    @Autowired
    private IStoreOrderCartInnerServiceSMO storeOrderCartInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartEventInnerServiceSMO storeOrderCartEventInnerServiceSMOImpl;
    @Autowired
    private IShopDistributionModeInnerServiceSMO shopDistributionModeInnerServiceSMOImpl;
    @Autowired
    private IStoreOrderCartSendInnerServiceSMO storeOrderCartSendInnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMOImpl;
    @Autowired
    private IAccountInnerServiceSMO accountInnerServiceSMOImpl;

    @Autowired
    private StoreOrderShareAcct storeOrderShareAcct;

    @Autowired
    private IStoreOrderInnerServiceSMO storeOrderInnerServiceSMOImpl;

    /**
     * @param storeOrderCartPo
     * @return 订单服务能够接受的报文
     */
    @Java110Transactional
    public ResponseEntity<String> update(StoreOrderCartPo storeOrderCartPo) {

        int flag = storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);

        if (flag > 0) {
            return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
        }

        return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
    }

    /**
     * 发货接口
     *
     * @param storeOrderCartPo 购物车信息
     * @param userId           操作员工
     * @return
     */
    @Override
    @Java110Transactional
    public ResponseEntity<String> sendOrderCart(StoreOrderCartPo storeOrderCartPo, String userId) {

        //判断自送还是 配送，自送直接为配送中 ，写入事件表为配送中，直接写userid.
        // 确认收货时写入配送中员工ID

        //配送的 更改状态为待配送
        //增加接单接口，接单后状态为配送中，写入事件表为 配送中，用户直接用userid，
        //结单 时修改状态为 待评价，写入事件表为 配送完成的
        ShopDistributionModeDto shopDistributionModeDto = new ShopDistributionModeDto();
        shopDistributionModeDto.setProductId(storeOrderCartPo.getProductId());
        List<ShopDistributionModeDto> shopDistributionModeDtos = shopDistributionModeInnerServiceSMOImpl.queryShopDistributionModes(shopDistributionModeDto);
        //自送 配送中
        if (shopDistributionModeDtos == null || shopDistributionModeDtos.size() < 1) {
            storeOrderCartPo.setState(StoreOrderCartDto.STATE_SENDING);

            StoreOrderCartEventPo storeOrderCartEventPo = new StoreOrderCartEventPo();
            storeOrderCartEventPo.setCartId(storeOrderCartPo.getCartId());
            storeOrderCartEventPo.setOrderId(storeOrderCartPo.getOrderId());
            storeOrderCartEventPo.setEventId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId));
            storeOrderCartEventPo.setEventObjType("S");
            storeOrderCartEventPo.setEventObjId(userId);
            storeOrderCartEventPo.setEventMsg("商家配送中");
            storeOrderCartEventPo.setShopId(storeOrderCartPo.getShopId());
            storeOrderCartEventPo.setEventType(StoreOrderCartEventDto.EVENT_TYPE_EXPEDITING_SENDING);
            int flag = storeOrderCartEventInnerServiceSMOImpl.saveStoreOrderCartEvent(storeOrderCartEventPo);

            if (flag < 1) {
                throw new IllegalArgumentException("保存购物车事件失败");
            }
        } else { //配送 待配送
            storeOrderCartPo.setState(StoreOrderCartDto.STATE_WAIT_SENDING);
        }
        int flag = storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);
        if (flag < 0) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
        }

        return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
    }

    /**
     * 接单接口
     *
     * @param storeOrderCartPo 购物车信息
     * @param userId           操作员工 receiving
     * @return
     */
    @Override
    @Java110Transactional
    public ResponseEntity<String> orderCartGrabbing(StoreOrderCartPo storeOrderCartPo, String userId) {

        //判断自送还是 配送，自送直接为配送中 ，写入事件表为配送中，直接写userid.
        // 确认收货时写入配送中员工ID

        //配送的 更改状态为待配送
        //增加接单接口，接单后状态为配送中，写入事件表为 配送中，用户直接用userid，
        //结单 时修改状态为 待评价，写入事件表为 配送完成的
        String requestId = DistributedLock.getLockUUID();
        String key = this.getClass().getSimpleName() + storeOrderCartPo.getOrderId();
        try {
            DistributedLock.waitGetDistributedLock(key, requestId);
            storeOrderCartPo.setState(StoreOrderCartDto.STATE_SENDING);
            int flag = storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);
            if (flag < 0) {
                return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
            }

            StoreOrderCartEventPo storeOrderCartEventPo = new StoreOrderCartEventPo();
            storeOrderCartEventPo.setCartId(storeOrderCartPo.getCartId());
            storeOrderCartEventPo.setOrderId(storeOrderCartPo.getOrderId());
            storeOrderCartEventPo.setEventId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId));
            storeOrderCartEventPo.setEventObjType("S");
            storeOrderCartEventPo.setEventObjId(userId);
            storeOrderCartEventPo.setEventMsg("商家配送中");
            storeOrderCartEventPo.setShopId(storeOrderCartPo.getShopId());
            storeOrderCartEventPo.setEventType(StoreOrderCartEventDto.EVENT_TYPE_EXPEDITING_SENDING);
            flag = storeOrderCartEventInnerServiceSMOImpl.saveStoreOrderCartEvent(storeOrderCartEventPo);

            if (flag < 1) {
                throw new IllegalArgumentException("保存购物车事件失败");
            }
        } finally {
            DistributedLock.releaseDistributedLock(requestId, key);
        }
        UserDto userDto = new UserDto();
        userDto.setUserId(userId);
        List<UserDto> userDtoList = userV1InnerServiceSMOImpl.queryUsers(userDto);
        Assert.isNotNull(userDtoList, "操作人员信息不存在，请检查数据");
        StoreOrderCartSendDto storeOrderCartSendDto = new StoreOrderCartSendDto();
        storeOrderCartSendDto.setCartId(storeOrderCartPo.getCartId());
        storeOrderCartSendDto.setShopId(storeOrderCartPo.getShopId());
        List<StoreOrderCartSendDto> storeOrderCartSendDtos = storeOrderCartSendInnerServiceSMOImpl.queryStoreOrderCartSends(storeOrderCartSendDto);
        if (storeOrderCartSendDtos != null && storeOrderCartSendDtos.size() > 0) {
            StoreOrderCartSendPo storeOrderCartSendPo = new StoreOrderCartSendPo();
            storeOrderCartSendPo.setSendUserId(userDtoList.get(0).getUserId());
            storeOrderCartSendPo.setSendUserName(userDtoList.get(0).getUserName());
            storeOrderCartSendPo.setState("1002");
            storeOrderCartSendPo.setSendUserTel(userDtoList.get(0).getTel());
            storeOrderCartSendPo.setSendTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
            storeOrderCartSendPo.setSendId(storeOrderCartSendDtos.get(0).getSendId());
            int flag = storeOrderCartSendInnerServiceSMOImpl.updateStoreOrderCartSend(storeOrderCartSendPo);
            if (flag < 1) {
                throw new IllegalArgumentException("修改派送状态失败");
            }
        }

        return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
    }

    /**
     * 释放订单接口
     *
     * @param storeOrderCartPo 购物车信息
     * @param userId           操作员工 receiving
     * @return
     */
    @Override
    @Java110Transactional
    public ResponseEntity<String> releaseRepair(StoreOrderCartPo storeOrderCartPo, String userId) {

        //判断自送还是 配送，自送直接为配送中 ，写入事件表为配送中，直接写userid.
        // 确认收货时写入配送中员工ID

        //配送的 更改状态为待配送
        //增加接单接口，接单后状态为配送中，写入事件表为 配送中，用户直接用userid，
        //结单 时修改状态为 待评价，写入事件表为 配送完成的

        storeOrderCartPo.setState(StoreOrderCartDto.STATE_WAIT_SENDING);
        int flag = storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);
        if (flag < 0) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
        }
        StoreOrderCartEventPo storeOrderCartEventPo = new StoreOrderCartEventPo();
        storeOrderCartEventPo.setCartId(storeOrderCartPo.getCartId());
        storeOrderCartEventPo.setOrderId(storeOrderCartPo.getOrderId());
        storeOrderCartEventPo.setEventId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId));
        storeOrderCartEventPo.setEventObjType("S");
        storeOrderCartEventPo.setEventObjId(userId);
        storeOrderCartEventPo.setEventMsg("放弃配送");
        storeOrderCartEventPo.setShopId(storeOrderCartPo.getShopId());
        storeOrderCartEventPo.setEventType(StoreOrderCartEventDto.EVENT_TYPE_EXPEDITING_SENDING_UP);
        flag = storeOrderCartEventInnerServiceSMOImpl.saveStoreOrderCartEvent(storeOrderCartEventPo);

        if (flag < 1) {
            throw new IllegalArgumentException("保存购物车事件失败");
        }
        UserDto userDto = new UserDto();
        userDto.setUserId(userId);
        List<UserDto> userDtoList = userV1InnerServiceSMOImpl.queryUsers(userDto);
        Assert.isNotNull(userDtoList, "操作人员信息不存在，请检查数据");
        StoreOrderCartSendDto storeOrderCartSendDto = new StoreOrderCartSendDto();
        storeOrderCartSendDto.setCartId(storeOrderCartPo.getCartId());
        storeOrderCartSendDto.setShopId(storeOrderCartPo.getShopId());
        List<StoreOrderCartSendDto> storeOrderCartSendDtos = storeOrderCartSendInnerServiceSMOImpl.queryStoreOrderCartSends(storeOrderCartSendDto);
        if (storeOrderCartSendDtos != null && storeOrderCartSendDtos.size() > 0) {
            StoreOrderCartSendPo storeOrderCartSendPo = new StoreOrderCartSendPo();
            storeOrderCartSendPo.setSendUserId(userDtoList.get(0).getUserId());
            storeOrderCartSendPo.setSendUserName(userDtoList.get(0).getUserName());
            storeOrderCartSendPo.setState("1004");
            storeOrderCartSendPo.setSendUserTel(userDtoList.get(0).getTel());
            storeOrderCartSendPo.setSendTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
            storeOrderCartSendPo.setSendId(storeOrderCartSendDtos.get(0).getSendId());
            flag = storeOrderCartSendInnerServiceSMOImpl.updateStoreOrderCartSend(storeOrderCartSendPo);
            if (flag < 1) {
                throw new IllegalArgumentException("修改派送状态失败");
            }
        }

        return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
    }

    @Override
    @Java110Transactional
    public ResponseEntity<String> receiveOrderCart(StoreOrderCartPo storeOrderCartPo) {
        storeOrderCartPo.setState(StoreOrderCartDto.STATE_WAIT_REPAIR);
        int flag = storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);
        if (flag < 0) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
        }
        StoreOrderCartEventDto storeOrderCartEventDto = new StoreOrderCartEventDto();
        storeOrderCartEventDto.setCartId(storeOrderCartPo.getCartId());
        storeOrderCartEventDto.setOrderId(storeOrderCartPo.getOrderId());
        storeOrderCartEventDto.setEventType(StoreOrderCartEventDto.EVENT_TYPE_EXPEDITING_SENDING);
        List<StoreOrderCartEventDto> storeOrderCartEventDtos = storeOrderCartEventInnerServiceSMOImpl.queryStoreOrderCartEvents(storeOrderCartEventDto);
        String eventObjId = null;
        if (!ListUtil.isNull(storeOrderCartEventDtos)) {
            eventObjId = storeOrderCartEventDtos.get(0).getEventObjId();
        } else {
            eventObjId = storeOrderCartPo.getPersonId();
        }
        StoreOrderCartEventPo storeOrderCartEventPo = new StoreOrderCartEventPo();
        storeOrderCartEventPo.setCartId(storeOrderCartPo.getCartId());
        storeOrderCartEventPo.setOrderId(storeOrderCartPo.getOrderId());
        storeOrderCartEventPo.setEventId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId));
        storeOrderCartEventPo.setEventObjType("S");
        storeOrderCartEventPo.setEventObjId(eventObjId);
        storeOrderCartEventPo.setEventMsg("配送完成");
        storeOrderCartEventPo.setShopId(storeOrderCartPo.getShopId());
        storeOrderCartEventPo.setEventType(StoreOrderCartEventDto.EVENT_TYPE_EXPEDITING_SENDING_SUCCESS);
        flag = storeOrderCartEventInnerServiceSMOImpl.saveStoreOrderCartEvent(storeOrderCartEventPo);

        if (flag < 1) {
            throw new IllegalArgumentException("保存购物车事件失败");
        }
        //todo 处理派送数据
        updateSendStateToFinish(storeOrderCartPo);

        StoreOrderCartDto storeOrderCartDto = new StoreOrderCartDto();
        storeOrderCartDto.setOrderId(storeOrderCartPo.getOrderId());
        storeOrderCartDto.setState(StoreOrderCartDto.STATE_SENDING);
        int count = storeOrderCartInnerServiceSMOImpl.queryStoreOrderCartsCount(storeOrderCartDto);
        if(count == 0){
            StoreOrderPo storeOrderPo = new StoreOrderPo();
            storeOrderPo.setOrderId(storeOrderCartPo.getOrderId());
            storeOrderPo.setState(StoreOrderDto.STATE_WAIT_REPAIR);
            storeOrderInnerServiceSMOImpl.updateStoreOrder(storeOrderPo);
        }

        // 分账处理
        StoreOrderDto storeOrderDto = new StoreOrderDto();
        storeOrderDto.setOrderId(storeOrderCartPo.getOrderId());
        List<StoreOrderDto> storeOrderDtos = storeOrderInnerServiceSMOImpl.queryStoreOrders(storeOrderDto);
        Assert.listOnlyOne(storeOrderDtos, "订单不存在");
        storeOrderShareAcct.shareAcct(storeOrderDtos.get(0));

        return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
    }

    /**
     * 派送数据状态修改为完成
     *
     * @param storeOrderCartPo
     */
    private void updateSendStateToFinish(StoreOrderCartPo storeOrderCartPo) {
        int flag;
        StoreOrderCartSendDto storeOrderCartSendDto = new StoreOrderCartSendDto();
        storeOrderCartSendDto.setCartId(storeOrderCartPo.getOrderId());
        storeOrderCartSendDto.setShopId(storeOrderCartPo.getShopId());
        List<StoreOrderCartSendDto> storeOrderCartSendDtos = storeOrderCartSendInnerServiceSMOImpl.queryStoreOrderCartSends(storeOrderCartSendDto);
        if (ListUtil.isNull(storeOrderCartSendDtos)) {
            return;
        }
        StoreOrderCartSendPo storeOrderCartSendPo = new StoreOrderCartSendPo();
        storeOrderCartSendPo.setState("1003");
        storeOrderCartSendPo.setFinishTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
        storeOrderCartSendPo.setSendId(storeOrderCartSendDtos.get(0).getSendId());
        flag = storeOrderCartSendInnerServiceSMOImpl.updateStoreOrderCartSend(storeOrderCartSendPo);
        if (flag < 1) {
            throw new IllegalArgumentException("修改派送状态失败");
        }
    }

}
